const moment = require('moment')
const md5 = require('md5')
class Classes {
  constructor() { }
  /* 获取列表 */
  async list(req, res) {
    let { pagesize, currentpage } = req.query
    pagesize = pagesize || 10
    currentpage = currentpage || 1
    let start = (currentpage - 1) * pagesize
    let total = await req.db.query('select count(1) count from `classes`', { type: req.db.QueryTypes.SELECT })
    let sql = 'select * from `classes` limit ' + start + ',' + pagesize
    let result = await req.db.query(sql, { type: req.db.QueryTypes.SELECT })
    res.send({
      error: 0,
      message: 'succes',
      total: total[0].count,
      data: result
    })
  }
  /* 编辑 */
  edit(req, res) {
    let { id, classname } = req.body
    let sql = 'update `classes` set `classname`="' + classname + '" where `id`="' + id + '"'
    req.db.query(sql).then((result) => {
      res.send({
        error: 0,
        message: 'succes',
      })
    })
  }
  /* 删除 */
  delete(req, res) {
    let { id } = req.query
    let sql = 'delete from `classes` where `id`="' + id + '"'
    req.db.query(sql).then((result) => {
      res.send({
        error: 0,
        message: 'succes',
      })
    })
  }

  /* 判断字段值是否存在 */
  isexist(req, res) {
    let { fieldname, fieldvalue } = req.query
    let sql = 'select count(1) count from `classes` where `' + fieldname + '`="' + fieldvalue + '"'
    req.db.query(sql).spread((result) => {
      if (result[0].count === 0) {
        res.send({
          error: 0,
          message: '不存在'
        })
      } else {
        res.send({
          error: 1,
          message: '存在'
        })
      }
    })
  }

  /* 添加 */
  add(req, res) {
    let { classname } = req.body
    let sql = 'insert into `classes` set `classname`="' + classname + '",`status`="1"'
    req.db.query(sql).then((result) => {
      res.send({
        info: req.session,
        error: 0,
        message: 'succes'
      })
    }).catch((error) => {
      console.log(error)
      res.send({
        error: 1,
        message: 'fail',
      })
    })
  }

}
module.exports = new Classes()